﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CreateMDB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string constr = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",textBox1.Text.Trim(),textBox2.Text.Trim(),textBox3.Text.Trim(),textBox4.Text.Trim()) ;
            string sql = "select name from sys.databases";
            DBHelper.Constr = constr;
            List<string> list = DBHelper.GetList(sql);
            comboBox1.DataSource = list;
            if (list.Count > 0) {
                panel2.Enabled = true;
            }
        }
        public string dir = "C://";
        private void button2_Click(object sender, EventArgs e)
        {
            if(DirBor.ShowDialog()==DialogResult.OK){
                dir = DirBor.SelectedPath;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string daldir = dir + "//DAL/";
            string blldir = dir + "//BLL/";
            string modeldir = dir + "//Model/";
            if (!Directory.Exists(daldir)) {
                Directory.CreateDirectory(daldir);
            }
            if (!Directory.Exists(blldir)) {
                Directory.CreateDirectory(blldir);
            }
            if (!Directory.Exists(modeldir))
            {
                Directory.CreateDirectory(modeldir);
            }
            string sql = "SELECT Name from  "+comboBox1.Text.Trim()+"..SysObjects Where XType='U' ORDER BY Name";
            List<string> list = DBHelper.GetList(sql);
            string constr = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", textBox1.Text.Trim(), comboBox1.Text.Trim(), textBox3.Text.Trim(), textBox4.Text.Trim());
            DBHelper.Constr = constr;
            foreach (string item in list)
            {
                string sqltable = "select name,usertype from syscolumns where id=object_id('"+item+"') ";
                DataTable temdt=DBHelper.GetDataSetBySQL(sqltable).Tables[0];
                CreateFileDir(modeldir,daldir, blldir, item, temdt);
            }
            MessageBox.Show("生成完成");
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="daldir"></param>
        /// <param name="blldir"></param>
        /// <param name="item"></param>
        /// <param name="cols"></param>
        private void CreateFileDir(string modeldir,string daldir, string blldir, string tablename, DataTable temdt)
        {
            string dalfile = daldir + tablename + "Service.cs";
            string bllfile = blldir +tablename + "Manager.cs";
            string modelfile = modeldir + tablename + ".cs";
            string bll = GetFile("Bll.txt");
            string dal = GetFile("Dal.txt");
            string model = GetFile("Model.txt");
            bll = bll.Replace("{tablename}",tablename);
            dal = dal.Replace("{tablename}", tablename);
            model = model.Replace("{tablename}", tablename);
            StringBuilder sb = new StringBuilder();
            StringBuilder addsb = new StringBuilder("insert into " + tablename);
            StringBuilder upsb = new StringBuilder("update "+tablename+" set ");
            StringBuilder addspr = new StringBuilder();
            StringBuilder upspr = new StringBuilder();
            string addsql1 = "";
            string addsql2 = "";
            string upstr1 = "";
            StringBuilder tableziduanSb = new StringBuilder();
            foreach (DataRow row in temdt.Rows)
            {
                string colname = row[0].ToString();
                int coltype = Convert.ToInt32(row[1]);
                if (coltype == 7)
                {
                    sb.Append("obj." + colname + "=Convert.ToInt32(sdr[\""+colname+"\"]);"+Environment.NewLine);
                }
                else
                {
                    sb.Append("obj." + colname + "=sdr[\"" + colname + "\"].ToString();" + Environment.NewLine);
                }
                if (colname != "Id")
                { 
                   addsql1+=colname+",";
                   addsql2 += "@" + colname + ",";
                   upstr1 += colname+"=@"+colname+",";
                   addspr.Append("new SqlParameter(\"@"+colname+"\",obj."+colname+"),");
                }
                upspr.Append("new SqlParameter(\"@" + colname + "\",obj." + colname + "),");
                if (coltype == 7)
                {
                    tableziduanSb.Append("\tpublic int "+colname+" {get;set;}"+Environment.NewLine);
                }
                else
                {
                    tableziduanSb.Append("\tpublic string " + colname + " {get;set;}" + Environment.NewLine);
                }
            }
            
            addsql1 = addsql1.Substring(0, addsql1.Length - 1);
            addsql2 = addsql2.Substring(0, addsql2.Length - 1);
            upstr1 = upstr1.Substring(0, upstr1.Length - 1);
            addsb.Append("("+addsql1+") values("+addsql2+") ");
            upsb.Append(upstr1+" where Id=@Id");
            string addsql = addsb.ToString();
            string upsql = upsb.ToString();
            string getallstr = sb.ToString();
            string addsprstr = addspr.ToString();
            string upsprstr = upspr.ToString();
            addsprstr = addsprstr.Substring(0, addsprstr.Length - 1);
            upsprstr = upsprstr.Substring(0, upsprstr.Length - 1);

            dal = dal.Replace("{getallstr}", getallstr).Replace("{addsql}", addsql).Replace("{addsqlspr}", addsprstr).Replace("{upsql}", upsql).Replace("{upsqlspr}", upsprstr);
            model=model.Replace("{tableziduan}", tableziduanSb.ToString());
            WriteFile(model,modelfile);
            WriteFile(bll,bllfile);
            WriteFile(dal, dalfile);
        }
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="bll"></param>
        /// <param name="bllfile"></param>
        private void WriteFile(string bll, string bllfile)
        {
             using(StreamWriter sw=new StreamWriter(bllfile,false)){
                 sw.Write(bll);
             }
        }
        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string GetFile(string p)
        {
            string path = Application.StartupPath + "//" + p;
            string str = string.Empty;
            using(StreamReader sr=new StreamReader(path)){
                str = sr.ReadToEnd();
            }
            return str;
        }  

        private void Form1_Load(object sender, EventArgs e)
        {
            panel2.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
         {
            string sql = "SELECT Name from  " + comboBox1.Text.Trim() + "..SysObjects Where XType='U' ORDER BY Name";
            List<string> list = DBHelper.GetList(sql);
            string constr = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", textBox1.Text.Trim(), comboBox1.Text.Trim(), textBox3.Text.Trim(), textBox4.Text.Trim());
            DBHelper.Constr = constr;
            StringBuilder sb = new StringBuilder();
            foreach (string item in list)
            {
                try
                {
                    string sqltable = string.Format(" alter table {0} add B1 nvarchar(200);alter table {0} add B2 nvarchar(200)", item);
                    DBHelper.zhixingsql(sqltable);
                }
                catch (Exception ec)
                {
                    sb.Append(ec.Message);
                }
            }
            MessageBox.Show("生成完成"+Environment.NewLine+sb.ToString());
        }
    }
}
